package thread.CyclicBarrier;


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

    public static void main(String[] args) throws InterruptedException {
        int size = 31;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(size,new Teacher("讲师"));

        for (int i = 0;i<size;i++){
            Thread.sleep(100);
            new Thread(new Student(cyclicBarrier),"学生"+i+1).start();
        }
    }

}
class Teacher implements Runnable{

    private String name;

    public static volatile  int i = 0;

    public Teacher(String name) {
        this.name = name;
        System.out.println(name+":开始签到");
    }


    @Override
    public void run() {
        if (i==0){
            System.out.println(name+":开始上课....");
        }else if (i==1){
            System.out.println(name+"放学之前签到");
        }else if (i==2){
            System.out.println(name+"放学");
        }else if(i==3){
            System.out.println(name+"同学们再见");
        }

    }
}
class Student implements Runnable{


    CyclicBarrier cyclicBarrier;

    public Student(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"：已签到");
        try {
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName()+"上课完成");
            Teacher.i = 1;
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName()+"：放学之前签到完成");
            Teacher.i = 2;
            cyclicBarrier.await();
            Teacher.i = 3;
            System.out.println(Thread.currentThread().getName()+"：老师再见");
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

    }
}

